const { app, BrowserWindow } = require('electron')
const path = require('path')

// 确保应用单实例运行
if (!app.requestSingleInstanceLock()) {
  app.quit()
}

function createTestWindow() {
  // 创建浏览器窗口
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'src/preload/index.js'),
      nodeIntegration: false,
      contextIsolation: true,
      // 添加浏览器特征
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
      webSecurity: false,
      allowRunningInsecureContent: true
    }
  })

  // 加载百度首页
  console.log('Attempting to load Baidu...')
  mainWindow.loadURL('https://www.baidu.com')

  // 监听页面加载完成事件
  mainWindow.webContents.on('did-finish-load', () => {
    console.log('Page loaded successfully')
  })

  // 监听加载失败事件
  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.log(`Failed to load page: ${errorCode} - ${errorDescription}`)
  })
}

app.whenReady().then(() => {
  createTestWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createTestWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('second-instance', () => {
  const mainWindow = BrowserWindow.getFocusedWindow()
  if (mainWindow) {
    if (mainWindow.isMinimized()) {
      mainWindow.restore()
    }
    mainWindow.focus()
  }
})